package com.ali.Reggie.controller;

import com.ali.Reggie.common.R;
import com.ali.Reggie.entity.User;
import com.ali.Reggie.service.UserService;
import com.ali.Reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.nio.cs.US_ASCII;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author ：ALi
 * @date ：Created in 2022/6/14 13:43
 * @description：用户控制类
 * @modified By：
 * @version: $
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){
        //1.获取手机号
        String phone = user.getPhone();
        String subject = "迅磊餐购登录验证码";
        if(StringUtils.isNotEmpty(phone)){
            //2.随机生成验证码
            String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",validateCode);
            String context = "欢迎使用迅磊餐购，登录验证码为: " + validateCode + ",五分钟内有效，请妥善保管!";
            //3.调用邮件服务或者短信服务
                // 真正地发送邮箱验证码
            userService.sendMsg(phone,subject,context);
            //4.需要将生成的验证码保存到Session中
            session.setAttribute(phone,validateCode);

            return R.success("验证码发送成功，请及时查看!");
        }

        return R.error("发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        if(session.getAttribute(phone) != null && session.getAttribute(phone).equals(code)){

            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(lambdaQueryWrapper);
            if(user == null){
                //说明没有查出来,处理新用户，自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        } else
            return R.error("登录失败");
    }
}